// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import FlyObj from "../pool/FlyObj";
import SpaceShip from "../pool/SpaceShip";
import FixedStar from "../pool/FixedStar";
import Planet from "../pool/Planet";
import * as Util from "../util";
import config from "../config";
import SpaceStation from "../pool/SpaceStation";
import BreakingMap from "../pool/Map";
import Rank from "../ui/rank";
import global from "../global";
const { ccclass, property } = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    @property({
        type: cc.Camera,
        displayName: "Camera",
        tooltip: "放置相机组件，方便移动视角"
    })
    camera: cc.Camera = null;

    @property({
        type: cc.Sprite,
        tooltip: "background",
        displayName: "background",
    })
    background: cc.Sprite = null;

    @property({
        type: cc.Button,
        displayName: "Pause",
        tooltip: "暂停按钮"
    })
    pauseButton: cc.Button = null;


    @property({
        type: cc.Button,
        displayName: "directRestart",
        tooltip: "直接重新开始"
    })
    directRestartButton: cc.Button = null;


    @property
    text: string = 'hello';

    @property({
        type: cc.Node,
        displayName: "popwindowPause",
        tooltip: "暂停弹窗界面"
    })
    popwindowPause: cc.Node = null;

    @property({
        type: cc.Node,
        displayName: "popwindowEnd",
        tooltip: "游戏终止弹窗界面"
    })
    popwindowEnd: cc.Node = null;

    @property({
        type: cc.Label,
        displayName: "breakLevel",
        tooltip: "当前闯关数"
    })
    breakLevelLabel: cc.Label = null;

    // LIFE-CYCLE CALLBACKS:
    public colliderManager: cc.CollisionManager = null; // 碰撞检测系统

    public gameshootsound: cc.AudioClip = null;
    public gameendsound: cc.AudioClip = null;

    // public allNode: cc.Node = new cc.Node();

    // public planetNode: cc.Node = new cc.Node();
    // public planet: Planet = null; //this.allNode.addComponent(Planet);

    // public fixedStarNode: cc.Node = new cc.Node();
    // public temFixedStar: FixedStar = null; //this.allNode.addComponent(FixedStar);

    public spaceShipNode: cc.Node = new cc.Node();
    public spaceShip: SpaceShip = null; //this.allNode.addComponent(SpaceShip);

    public spaceStationNode: cc.Node = new cc.Node();
    public spaceStation: SpaceStation = null;

    public starNode: cc.Node[] = [];                  // 所有星球的节点列表
    // public star: FlyObj[] = null;                       // 所有星球的脚本实例（实例挂载在星球节点上，即this.starNode[i]包含this.star[i]这个脚本

    public contineButton: cc.Button = null;
    public backToMenuButton1: cc.Button = null;

    public winOrLoseLabel: cc.Label = null;
    public restartButton: cc.Button = null;
    public backToMenuButton2: cc.Button = null;

    public isOut: boolean = false;
    public x = 0;
    public isPause: boolean = false;

    public gameMode: number = 0; // 游戏模式 0：闯关模式
    public nowBreakingLevel = 0; // 当前关卡
    public breakingMap = new BreakingMap();

    public needUpdate: boolean = true;


    onLoad() {
        // cc.assetManager.loadRemote(config.backgroundURL, { ext: '.jpg' }, (err, texture) => {

        //     let temWidth = 720;
        //     let temheight = 1280;
        //     this.background.spriteFrame = new cc.SpriteFrame(texture); // 传入图片
        //     this.background.node.width = temWidth;          // 将图片形状还原到原本大小
        //     this.background.node.height = temheight;
        // })

        cc.assetManager.loadRemote(config.GameShootSoundURL, { ext: '.mp3' }, (err, AudioClip) => {
            this.gameshootsound = AudioClip;
        })

        cc.assetManager.loadRemote(config.GameEndSoundURL, { ext: '.mp3' }, (err, AudioClip) => {
            this.gameendsound = AudioClip;
        })
        this.nowBreakingLevel = global.nowBreakingLevel;
        this.breakLevelLabel.string = (this.nowBreakingLevel + 1).toString();
        // if (global.nowBreakingLevel >= 0) {
        //     console.log(global.nowBreakingLevel);
        //     this.nowBreakingLevel = global.nowBreakingLevel;
        //     this.breakLevelLabel.string = (this.nowBreakingLevel + 1).toString();
        // }
        // else {
        //     Util.getCloudBreaking((res) => {
        //         if (res.data.length == 0) {
        //             global.maxBreakingLevel = global.nowBreakingLevel = this.nowBreakingLevel = 0;
        //             Util.updataCloudBreaking(0);
        //         }
        //         else {
        //             global.maxBreakingLevel = global.nowBreakingLevel = this.nowBreakingLevel = res.data.breakLevel;
        //         }
        //         this.breakLevelLabel.string = (this.nowBreakingLevel + 1).toString();
        //     })
        // }

        this.setStatuActive(true);

        this.initGame();
        Rank.setScore(0);
        // console.log("game_onload");

        // 设置监听事件
        this.node.on(cc.Node.EventType.TOUCH_START, (event) => this.onTouchStart(event));
        this.restartButton && this.restartButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.restart(); });
        // this.restartButton && this.restartButton.node.on(cc.Node.EventType.TOUCH_END, (event) => {this.restartButton.node.active = false});
        this.contineButton && this.contineButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.gameContinue() });
        this.backToMenuButton1 && this.backToMenuButton1.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.backToMenu() });
        this.pauseButton && this.pauseButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.gamePause() });
        this.directRestartButton && this.directRestartButton.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.restart(); });
        this.backToMenuButton2 && this.backToMenuButton2.node.on(cc.Node.EventType.TOUCH_START, (event) => { this.backToMenu() });

        /*
        // this.allNode.parent = this.node;
        // this.planetNode.parent = this.node;
        // this.fixedStarNode.parent = this.node;
        // this.spaceShipNode.parent = this.node;

        // this.allNode.group = "group1";

        // this.allNode.name = "p1";
        // this.planetNode.name = "pp1";
        // this.fixedStarNode.name = "f1";
        // this.spaceShipNode.name = "s1";

        // this.planet = this.planetNode.addComponent(Planet);
        // this.spaceShip = this.spaceShipNode.addComponent(SpaceShip);
        // this.temFixedStar = this.fixedStarNode.addComponent(FixedStar);
        
        // this.planet.nodeName = "planet";
        // this.spaceShip.nodeName = "SpaceShip1";
        // this.temFixedStar.nodeName = "FixedStar1";

        // this.planet.node.setPosition(-100,-20);
        // console.log("game_onload");
        // setTimeout(() => {console.log("aaaaaaaa");this.spaceShip.setAnchorPlanet(this.planet);}, 100);//延迟100ms设置轨道
        
        // 开始碰撞检测
        // this.colliderManager = cc.director.getCollisionManager();
        // this.colliderManager.enabled = true;                // 开启碰撞检测
        // this.colliderManager.enabledDebugDraw = true;       // 显示碰撞检测边缘
        // this.colliderManager.enabledDrawBoundingBox = true; // 显示碰撞检测边缘
        // cc.director.getPhysicsManager().enabled = true;
        */


    }

    start() {
    }

    update(dt) {
        // this.x+=1;

        // console.log(this.starNode[0].name);
        //console.log(this.camera);
        // this.camera.node.setPosition(0, this.x);
        // this.backGround.node.setPosition(0, this.x);
        // console.log(this.spaceShip.node);
        if (!this.isPause && this.needUpdate) {
            this.cheakIsOut();
            if (this.isOut || this.spaceShip.isDestroy) {
                this.gameEnd('Lose');
            }
            else if (this.cheakIsSuccess()) {
                this.nowBreakingLevel++;
                if (this.nowBreakingLevel > global.maxBreakingLevel) {
                    global.maxBreakingLevel = this.nowBreakingLevel;
                    Util.updataCloudBreaking(this.nowBreakingLevel);
                }
                Rank.setScore(this.nowBreakingLevel);
                if (this.cheakIsBreakingSuccess()) {
                    this.gameEnd('Win');
                }
                else {
                    global.nowBreakingLevel = this.nowBreakingLevel;
                    this.breakLevelLabel.string = (this.nowBreakingLevel + 1).toString();
                    this.restart();
                }
                //console.log(this.cheakIsSuccess());

            }
            else {
                this.spaceShip.shipMoving(dt);
            }
        }

        // this.fixedStarNode.setPosition(0, -640);
        // console.log(this.x);
    }

    /**
     * 检查当前的spaceShip是否移出屏幕，同步修改this.isOut
     */
    cheakIsOut() {
        let nowX = this.spaceShip.node.x;
        let nowY = this.spaceShip.node.y;
        let nowWidth = this.node.width / 2;
        let nowHeight = this.node.height / 2;
        this.isOut = nowX > nowWidth || nowX < -nowWidth || nowY > nowHeight || nowY < -nowHeight
        return this.isOut;
    }

    /**
     * 检查是否遍历完了所有行星
     */
    cheakIsSuccess() {
        if (this.starNode.length < 0) {
            return false;
        }
        for (let i = 0; i < this.starNode.length; i++) {
            if (this.starNode[i].getComponent(this.starNode[i].name).Havespaceship <= 0)
                return false;
        }
        return true;
    }

    cheakIsBreakingSuccess() {
        // console.log(this.nowBreakingLevel > this.breakingMap.getLevelNum() - 1);
        return this.nowBreakingLevel > this.breakingMap.getLevelNum() - 1;
    }

    /**
     * 屏幕被点击时候的回应
     * @param event 系统返回的参数
     */
    onTouchStart(event) {
        // console.log(event);
        if (this.spaceShip.isMoving) {
            // console.log("it is moving");
            return;
        }
        else {
            if (this.gameshootsound) cc.audioEngine.playEffect(this.gameshootsound, false);
        }
        this.spaceShip.isMoving = true;
    }

    /**
     * 实现游戏界面的初始化
     */
    initGame() {
        [this.contineButton, this.backToMenuButton1] = this.popwindowPause.getComponentsInChildren(cc.Button);
        this.popwindowPause.active = false;

        this.winOrLoseLabel = this.popwindowEnd.getComponentInChildren(cc.Label);
        [this.restartButton, this.backToMenuButton2] = this.popwindowEnd.getComponentsInChildren(cc.Button);
        this.popwindowEnd.active = false;

        this.spaceShipNode.parent = this.node;
        this.spaceStationNode.parent = this.node;

        this.spaceShip = this.spaceShipNode.addComponent(SpaceShip);
        this.spaceStation = this.spaceStationNode.addComponent(SpaceStation);

        // let firstPlanet = this.createStar("Planet", {x: 0, y: -500});
        // setTimeout(() => {this.spaceShip.setAnchorPlanet(firstPanet);}, 200);//延迟100ms设置轨道
        this.spaceShip.setAnchorPlanet(this.spaceStation, true);
        //this.levelBreakingMode();
        this.fileWithMap();
        this.colliderManager = cc.director.getCollisionManager();
        this.colliderManager.enabled = true;                // 开启碰撞检测
        // this.colliderManager.enabledDebugDraw = true;       // 显示碰撞检测边缘
        // this.colliderManager.enabledDrawBoundingBox = true; // 显示碰撞检测边缘 

        // this.restartButton && (this.restartButton.node.active = false);
        // console.log(global.nowBreakingLevel);

    }

    /**
     * 游戏结束，显示游戏结束跳转弹窗
     * @param status 当前的结束状态（Win/Lose
     */
    gameEnd(status: string) {
        this.needUpdate = false;
        this.setStatuActive(false);
        this.popwindowEnd.active = true;
        if (status == 'Win') {
            this.winOrLoseLabel.string = '恭喜过关';
        }
        else if (status == 'Lose') {
            if (this.gameendsound) cc.audioEngine.playEffect(this.gameendsound, false);
            this.winOrLoseLabel.string = '闯关失败';
        }
    }

    /**
     * 切换到游戏暂停状态
     */
    gamePause() {
        this.isPause = true;
        this.setStatuActive(false);
        this.popwindowPause.active = true;
    }

    /**
     * 由暂停状态切换到游戏状态
     */
    gameContinue() {
        this.isPause = false;
        this.setStatuActive(true);
        this.popwindowPause.active = false
    }

    /**
     * 返回主菜单
     */
    backToMenu() {
        cc.director.loadScene("Home");
    }

    /**
     * 重新开始游戏
     */
    restart() {
        this.popwindowEnd.active = false;
        this.setStatuActive(true);
        this.cleanMap();
        this.fileWithMap();
        this.spaceStationNode.active = true;
        this.spaceShip.setAnchorPlanet(this.spaceStation, true);
        this.needUpdate = true;
    }


    cleanMap() {
        while (this.starNode.length > 0) {
            let temNode = this.starNode.shift();
            temNode.destroy();
        }
    }

    /**
     * 在本节点中创建一个星球类，加入到this.starNode中
     * @param className 创建的星球类的类名，如"Planet"
     * @param Info 创建节点位置和大小
     */
    createStar(className, Info: NodeInfoPara = { x: 0, y: 0, width: 100 }) {
        let temNode = new cc.Node();
        temNode.parent = this.node;         // 每次new一个结点都要先设置父节点，不然坐标会有问题
        let temStar = temNode.addComponent(className);
        temStar.setInfo(Info);
        this.starNode.push(temNode);
        // console.log({ this: this.node.x, now: temNode.y, button: this.restartButton.node.zIndex });
        return temStar;
    }

    /**
     * 实现创建星球来填充画布的过程
     * @param mode 填充模式（扩充内容）
     */
    fileWithMap(mode = 0) {
        if (this.gameMode == 0) {
            let nowBreakingMap = this.breakingMap.getMap(this.nowBreakingLevel);
            for (var i in nowBreakingMap) {
                // console.log({ i: i, ni: nowBreakingMap[i] });
                for (let j = 0; j < nowBreakingMap[i].num; j++) {
                    // console.log(nowBreakingMap[i].name, nowBreakingMap[i].value[j]);
                    this.createStar(nowBreakingMap[i].name, nowBreakingMap[i].value[j]);
                }
            }
        }
        if (this.gameMode == 1) {
            let temEndNode = null;
            if (this.starNode.length == 0) {
                temEndNode = this.spaceStationNode;
            }
            else {
                temEndNode = this.starNode[this.starNode.length - 1];
            }
            let temX = temEndNode.x;
            let temY = temEndNode.y;
            let temWidth = temEndNode.width;
            let temClass = this.getRandomStarClass();
            // let temClass = "Planet";
            while (temY < this.node.height / 2 - config.maxWidth - this.spaceShip.node.width) {
                // let temStar = temEndNode.getComponent(temEndNode.name);
                temY += this.spaceShip.node.width;
                temY = Util.randomNum(temY + 50, temY + 150);
                temX = this.getRandomX({ x: temX, width: temWidth });
                temClass = this.getRandomStarClass();
                // console.log({endX:temX});
                temWidth = Util.randomNum(config.minWidth, config.maxWidth);
                this.createStar(temClass, { x: temX, y: temY, width: temWidth, height: temWidth });
                // console.log(this.spaceShip.node);
            }
        }
    }

    /**
     * 根据Info中现节点的x与width在合适的范围中返回随机值
     * @param Info {x,width} 包含现节点的x与width
     * @param mode 选取方式:0：在左右中随机选，1：在左边随机选，2：在右边随机选
     */
    getRandomX(Info: { x, width }, mode: number = 0) {
        if (mode == 0)
            return this.getRandomX(Info, Math.round(Math.random()));
        else if (mode == 1) {
            let leftMin = - (this.node.width / 2) + this.spaceShip.node.width + config.maxWidth / 2;
            let leftMax = Info.x - (Info.width + config.maxWidth) / 2 - this.spaceShip.node.width;
            // console.log({Info: Info, leftMin: leftMin, leftMax: leftMax});
            if (leftMin >= leftMax)
                return this.getRandomX(Info, 2);
            // console.log({leftMin: leftMin, leftMax: leftMax});
            return Util.randomNum(leftMin, leftMax);
        }
        else {
            let rightMin = Info.x + (Info.width + config.maxWidth) / 2 + this.spaceShip.node.width;
            let rightMax = this.node.width / 2 - this.spaceShip.node.width - config.maxWidth / 2;
            // console.log({rightMin: rightMin, rightMax: rightMax});
            if (rightMin >= rightMax)
                return this.getRandomX(Info, 1);
            // console.log({rightMin: rightMin, rightMax: rightMax});
            return Util.randomNum(rightMin, rightMax);
        }
    }

    /**
     * 随机获取星球类，现在为等可能获取（可拓展）
     */
    getRandomStarClass() {
        let classNum = 2;
        let random = Math.floor(Math.random() * classNum);
        if (random < 1)
            return "Planet";
        else
            return "FixedStar";
    }

    setStatuActive(isActive) {
        this.pauseButton.node.active = isActive;
        this.directRestartButton.node.active = isActive;
    }
}
